package com.jxt.myjxtmanager.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jxt.myjxtmanager.BaseActivity;
import com.jxt.myjxtmanager.R;
import com.jxt.myjxtmanager.db.SaleUser;
import com.jxt.myjxtmanager.db.SaleUserModel;
import com.jxt.myjxtmanager.utils.Tools;
import com.jxt.myjxtmanager.utils.imageloader.ImageLoaderAbs;

import java.io.File;

/**
 * Created by qm on 2017/3/13 0013.
 */
public class MyInfoActivity extends BaseActivity
        implements DialogInterface.OnClickListener {

    private RelativeLayout rel_change_photo;
    private RelativeLayout rel_change_name;
    private ImageView iv_show_avatar;
    private TextView tv_name;
    private TextView tv_phone;

    public static final int IMAGE_REQUEST_CODE = 3;
    public static final int CAMERA_REQUEST_CODE = 1;
    public static final int RESULT_REQUEST_CODE = 2;
    private SaleUser saleUser;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_info;
    }

    @Override
    protected void initView() {
        setToolbarTitle("我的资料");
        setToolbarNavigationIcon(R.drawable.ic_left_return);
        rel_change_photo = (RelativeLayout) findViewById(R.id.rel_change_photo);
        rel_change_name = (RelativeLayout) findViewById(R.id.rel_change_name);
        iv_show_avatar = (ImageView) findViewById(R.id.iv_show_avatar);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        rel_change_photo.setOnClickListener(this);
        rel_change_name.setOnClickListener(this);
    }

    @Override
    public void onClickLeftMenu() {
        super.onClickLeftMenu();
    }


    @Override
    protected void onResume() {
        super.onResume();
        saleUser = SaleUserModel.getInstance().loadCurrentSaleUsers();
        if (saleUser == null) return;
        if (!TextUtils.isEmpty(saleUser.getHead_img())) {
            ImageLoaderAbs.getInstance().roundDisplayImage(
                    saleUser.getHead_img(), iv_show_avatar,
                    R.drawable.icon_headportrait);
        }
        if (!TextUtils.isEmpty(saleUser.getTrue_name())) {
            tv_name.setText(saleUser.getTrue_name());
        }
        if (!TextUtils.isEmpty(saleUser.getPhone())) {
            tv_phone.setText(saleUser.getPhone());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_change_name:
                startActivity(new Intent(MyInfoActivity.this, ChangeUserNameActivity.class));
                break;
            case R.id.rel_change_photo:
                showDialog(this);
                break;
        }
    }

    public void showDialog(DialogInterface.OnClickListener instance) {
        String[] items = new String[]{
                mContext.getString(R.string.select_update_native),
                mContext.getString(R.string.select_update_camera)};
        new AlertDialog.Builder(mContext)
                .setTitle(mContext.getString(R.string.toast_setting_avarat))
                .setItems(items, instance)
                .setNegativeButton(mContext.getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

        switch (which) {
            case 0:
                Intent intentFromGallery = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
                break;
            case 1:
                if (Tools.hasSdcard()) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {//动态检测相机权限
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.CAMERA},
                                CAMERA_REQUEST_CODE);
                    } else {
                        startActivityForResult(startCamera(), CAMERA_REQUEST_CODE);
                    }
                } else {
                    Toast.makeText(this, "没有sdcard", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 图片返回的地址
     */
    Uri photoUri;

    /**
     * 启动相机
     *
     * @return
     */
    public Intent startCamera() {
        ContentResolver cr = mContext.getContentResolver();
        photoUri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        return in;
    }

    /**
     * 启动裁剪界面
     *
     * @param data
     */
    public Intent startPhotoZoom(Intent data) {
        Uri uri;
        if (data == null) {
            uri = photoUri;
        } else {
            uri = data.getData();
        }
        Intent intent = new Intent();
        intent.setData(uri);
        intent.setClass(mContext, ClipImageActivity.class);
        return intent;
    }

    private void updataPicture(Intent data) {

        String path = data.getExtras().getString("images");
        final File file = new File(path);
        if (file == null || !file.exists())
            return;
//        ImageLoaderAbs.getInstance().displayImage("file://" + path, iv_show_avatar);

        ImageLoaderAbs.getInstance().roundDisplayImage(
                "file://" + path, iv_show_avatar,
                R.drawable.icon_headportrait);
        if (saleUser == null) {
            saleUser = SaleUserModel.getInstance().loadCurrentSaleUsers();
        }
        saleUser.setHead_img("file://" + path);
        SaleUserModel.getInstance().insertOrReplace(saleUser);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {

            case IMAGE_REQUEST_CODE:
                startActivityForResult(startPhotoZoom(data), RESULT_REQUEST_CODE);
                break;

            case CAMERA_REQUEST_CODE:
                startActivityForResult(startPhotoZoom(data), RESULT_REQUEST_CODE);
                break;

            case RESULT_REQUEST_CODE:
                if (data != null) {
                    updataPicture(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
